﻿using IdentityModel;
using IdentityServer.Configuration;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Entities;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace IdentityServer.Data
{
    public class ConfigurationDbContextSeed
    {
        public async Task SeedAsync(ConfigurationDbContext context, IConfiguration configuration)
        {
            //callbacks urls from config:
            var clientUrls = new Dictionary<string, string>();
            clientUrls.Add("WeChat", configuration.GetValue<string>("WeChatClient"));
            clientUrls.Add("WeChatWeb", configuration.GetValue<string>("WeChatWebClient"));
            clientUrls.Add("SystemWeb", configuration.GetValue<string>("SystemWebClient"));

            if (!context.Clients.Any())
            {
                foreach (var client in Config.GetClients(clientUrls))
                {
                    context.Clients.Add(client.ToEntity());
                }
                await context.SaveChangesAsync();
            }
            //else
            //{
            //    List<ClientRedirectUri> oldRedirects = (await context.Clients.Include(c => c.RedirectUris).ToListAsync())
            //        .SelectMany(c => c.RedirectUris)
            //        .Where(ru => ru.RedirectUri.EndsWith("/o2c.html"))
            //        .ToList();

            //    if (oldRedirects.Any())
            //    {
            //        foreach (var ru in oldRedirects)
            //        {
            //            ru.RedirectUri = ru.RedirectUri.Replace("/o2c.html", "/oauth2-redirect.html");
            //            context.Update(ru.Client);
            //        }
            //        await context.SaveChangesAsync();
            //    }
            //}

            if (!context.IdentityResources.Any())
            {
                foreach (var resource in Config.GetResources())
                {
                    context.IdentityResources.Add(resource.ToEntity());
                }
                await context.SaveChangesAsync();
            }

            if (!context.ApiResources.Any())
            {
                foreach (var api in Config.GetApis())
                {
                    context.ApiResources.Add(api.ToEntity());
                }

                await context.SaveChangesAsync();
            }

            if (!context.ApiScopes.Any())
            {
                foreach (var resource in Config.ApiScopes)
                {
                    context.ApiScopes.Add(resource.ToEntity());
                }
               await context.SaveChangesAsync();
            }
        }

        public async Task SeedDefaultUserAsync(IdentityServerContext context)
        {
            if (!context.Users.Any())
            {
                IPasswordHasher<WeChatIdentity.Models.ApplicationUser> passwordHasher = new PasswordHasher<WeChatIdentity.Models.ApplicationUser>();
                var defaultUser = new WeChatIdentity.Models.ApplicationUser("administrator", "ABCDEFG", "管理员","","","福建","厦门市","中国");
                defaultUser.PasswordHash = passwordHasher.HashPassword(defaultUser, "sa123");
                defaultUser.NormalizedUserName = defaultUser.UserName;
                //defaultUser.SetClaims("role", "administrator");
                context.Users.Add(defaultUser);
                //用户身份
                IdentityUserClaim<string> claims = new IdentityUserClaim<string>();
                claims.UserId = defaultUser.Id;
                claims.ClaimType = JwtClaimTypes.Role;
                claims.ClaimValue = "administrator";
                context.UserClaims.Add(claims);

                await context.SaveChangesAsync();
            }
        }
    }
}
